package app.tasks.schedule;

import app.env.Data;
import app.agent.Schedule;
import app.util.AppUtils;
import jade.core.AID;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Name: SortSignal
 * @Description: 对信号值排序，将信号最低的30%的代理设置为随机移动，将其他的搜索代理设为有方向探测移动。
 * @Author: colfish
 * @Date: 2021/4/25
 */
public class SortSend extends OneShotBehaviour {

    private static final long serialVersionUID = -598138569571175074L;
    private Schedule schedule;
    private Logger logger = LogManager.getLogger(this.getClass());
    private int nextState;


    public SortSend(Schedule schedule){
        nextState = 1;
        this.schedule = schedule;
    }
    @Override
    public void action() {
        // 2. 对信号值排序
//        long stime = System.currentTimeMillis();
        List<Integer> tempSignals = new ArrayList<>();
        for(String signal : Data.searchSignals.values()){
            tempSignals.add(Integer.parseInt(signal));
        }
        tempSignals.sort(Integer::compareTo);
        int axis = (int) Math.round(tempSignals.size()*0.3);
        int axisSignal = tempSignals.get(axis);
        // 3. 设置通知移动点
        for(Map.Entry<String, String> seaSignal: Data.searchSignals.entrySet()){
            String name = seaSignal.getKey();
            int signal = Integer.parseInt(seaSignal.getValue());
            // 发送消息
            ACLMessage message = new ACLMessage(ACLMessage.INFORM);
            AID receiver = new AID(name, AID.ISLOCALNAME);
            // 将移动消息发送给搜索代理
            message.addReceiver(receiver);
            if(signal <= axisSignal){
                // 信号值小于等于全部信号值中30%的代理，随机移动
                message.setContent(Data.SEARCH_MOVE_RANDOM);
            }
            else {
                // 其他的，有方向移动，移动到搜索范围内信号最大的坐标处
                // 将移动到最大信号值的消息送给搜索代理
                message.setContent(Data.SEARCH_MOVE_MAX);
            }
            schedule.send(message);
            logger.info(AppUtils.logMessage(schedule.getAID(), receiver, message));
            schedule.receiveCount--;
        }
        // 1. 重置receiveCount
        Data.receivedSearch.clear();
        nextState = 1;
        logger.info("SortSignal Completely!");
//        long etime = System.currentTimeMillis();
//
//        Data.Stime = Data.Stime + (etime - stime);
//        Data.Scnt++;
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public int onEnd() {
        return nextState;
    }
}
